package summary;

/**
 * @Author: 海琳琦
 * @Date: 2022/4/20 12:05
 * https://leetcode-cn.com/problems/word-search/
 */
public class Title79 {

    int n, m;
    public boolean exist(char[][] board, String word) {
        n = board.length;
        m = board[0].length;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (board[i][j] == word.charAt(0)) {
                    if (dfs(board, word, i, j, 0)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private boolean dfs(char[][] board, String word, int i, int j, int curIndex) {
        if (i < 0 || i >= n || j < 0 || j >= m || board[i][j] == '0' || board[i][j] != word.charAt(curIndex)) {
            return false;
        }
        if (curIndex == word.length() - 1) {
            return true;
        }
        char c = board[i][j];
        board[i][j] = '0';
        int[] dx = {-1, 1, 0, 0};
        int[] dy = {0, 0, -1, 1};
        for (int k = 0; k < 4; k++) {
            if (dfs(board, word, i + dx[k], j + dy[k], curIndex + 1)) {
                return true;
            }
        }
        board[i][j] = c;
        return false;
    }

    public static void main(String[] args) {

    }
}
